<?php

namespace app\rent\controller;

use think\Controller;

class Lease extends Controller
{
    protected $BusinessModel;
    protected $LeaseModel;
    protected $ProductModel;
    protected $RecordModel;
    protected $ExpressqueryModel;
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->ProductModel = model('Product.Product');
        $this->LeaseModel = model('Lease');
        $this->RecordModel = model('Business.Record');
        $this->ExpressqueryModel = model('Expressquery');
    }
    //添加
    public function add()
    {

        $params = $this->request->param();
        $params=json_decode($params['data'],true);
        
        // if (isset($_FILES['card']) &&  $_FILES['card']['size'][0] > 0 && $_FILES['card']['error'][0] == 0) {
        //     var_dump(1);
        //     exit;
        // }
        // var_dump(0);
        // exit;
        $busid = $params['busid'] ?? 0;
        $proid = $params['proid'] ?? 0;
        //   用户是否存在 
        $businessinfo = $this->BusinessModel->find($busid);
        if (!$businessinfo) {
            $this->error('用户不存在');
        }
        //    商品是否存在
        $productinfo = $this->ProductModel->find($proid);
        if (!$productinfo) {
            $this->error('产品不存在');
        }

        // 判断用户余额
        $money = bcsub($businessinfo['money'], $params['price'], 2);

        if ($money < 0) {
            $this->error('余额不足，请去充值');
        }

        $this->BusinessModel->startTrans();
        $this->LeaseModel->startTrans();
        $this->RecordModel->startTrans();
        // 租赁数据
        $LeaseData = [
            'busid' => $busid,
            'proid' => $proid,
            'rent' => $params['rent'],
            'price' => $params['price'],
            'endtime' => strtotime($params['endtime']),
            'address' => $params['address'],
            'status' => '1',
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district'],
        ];

        // 判断是否有证件
        if (isset($_FILES['card']) &&  $_FILES['card']['size'][0] > 0 && $_FILES['card']['error'][0] == 0) {
            $res = uploads('card');
            if ($res['code'] == 0) {
                $this->error($res['msg']);
            }
            $LeaseData['card'] = $res['data'];
        }
        // 生成租赁订单
        $LeaseStatus = $this->LeaseModel->validate('common/Lease')->save($LeaseData);

        if ($LeaseStatus === false) {
            $this->error($this->LeaseModel->getError());
        }

        // 用户表余额更新
        $BusinessStatus = $this->BusinessModel->where('id', $busid)->update(['money' => $money]);

        if ($BusinessStatus === false) {
            $this->LeaseModel->rollback();
            $this->error('余额更新失败');
        }
        //    消费数据
        $RecordData = [
            'total' => $params['price'],
            'content' => '租的车子名称：' . $productinfo['name'] . '，消费的金额：￥' . $params['price'] . '元',
            'busid' => $busid,
            'state' => '4'
        ];
        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

        if ($RecordStatus === false) {
            $this->BusinessModel->rollback();
            $this->LeaseModel->rollback();
            $this->error($this->RecordModel->getError());
        }
        $this->BusinessModel->commit();
        $this->LeaseModel->commit();
        $this->RecordModel->commit();
        $this->success('租赁成功');
    }
    // 租赁列表
    public function index()
    {
        $status = $this->request->param('status', '', 'trim');
        $busid = $this->request->param('busid', '', 'trim');
        //   用户是否存在 
        $businessinfo = $this->BusinessModel->find($busid);
        if (!$businessinfo) {
            $this->error('用户不存在');
        }
        $where = ['busid' => $busid];
        if ($status) {
            $where['lease.status'] = $status;
        }

        $list = $this->LeaseModel->where($where)->with('product')->order('createtime', 'desc')->select();
        if ($list) {
            $this->success('', '', $list);
        }
        $this->error('暂无数据');
    }
    // 租赁订单详情
    public function info()
    {
        $leaseid = $this->request->param('leaseid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');
        //   用户是否存在
        $businessinfo = $this->BusinessModel->find($busid);
        if (!$businessinfo) {
            $this->error('用户不存在');
        }
        $info = $this->LeaseModel->with(['product', 'business'])->find($leaseid);
        if ($info) {

            $this->success('', '', $info);
        }
        $this->error('数据不存在');
    }
    // 物流信息
    public function flow()
    {
        $leaseid = $this->request->param('leaseid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');
        //   用户是否存在
        $businessinfo = $this->BusinessModel->find($busid);
        if (!$businessinfo) {
            $this->error('用户不存在');
        }
        $info = $this->LeaseModel->with(['product'])->find($leaseid);
        // 判断是否有物流信息
        if ($info['expcode']) {
            if (cache($info['expcode'])) {
                $express = cache($info['expcode']);
                $info['express'] = $express;
            } else {
                $res = query_express($info['expcode']);

                if ($res['result'] == false) {
                    $this->error($res['msg']);
                }
                // 设置缓存数据
                cache($info['expcode'],$res['data']);
                $info['express'] = $res['data'];
            }
        }
        $this->success('','',$info);
    }
     // 确认收货
     public function confirm()
     {
         $busid = $this->request->param('busid', 0, 'trim');
         $leaseid = $this->request->param('leaseid', 0, 'trim');
 
         $businessinfo = $this->BusinessModel->find($busid);
         if (!$businessinfo) {
             $this->error('用户不存在');
         }
 
         $leaseinfo = $this->LeaseModel->find($leaseid);
 
         if (!$leaseinfo) {
             $this->error('订单不存在');
         }
 
         $result = $this->LeaseModel->where('id', $leaseid)->update(['status' => '3']);
 
         if ($result === false) {
             $this->error('操作失败');
         } else {
             $this->success('操作成功');
         }
     }
 
     // 获取物流公司
     public function express()
     {
         $data = $this->ExpressqueryModel->field('id as value,name as text')->select();
 
         $this->success('', '', $data);
     }
 
     // 归还商品
     public function recovery()
     {
         $busid = $this->request->param('busid', 0, 'trim');
         $leaseid = $this->request->param('leaseid', 0, 'trim');
         $busexpid = $this->request->param('busexpid', 0, 'trim');
         $busexpcode = $this->request->param('busexpcode', '', 'trim');
 
         $businessinfo = $this->BusinessModel->find($busid);
         if (!$businessinfo) {
             $this->error('用户不存在');
         }
 
         $leaseinfo = $this->LeaseModel->find($leaseid);
 
         if (!$leaseinfo) {
             $this->error('订单不存在');
         }
 
         $data = [
             'id' => $leaseid,
             'busexpid' => $busexpid,
             'busexpcode' => $busexpcode,
             'status' => '4',
         ];
      
 
         $result = $this->LeaseModel->isUpdate()->save($data);
 
         if ($result === false) {
             $this->error('操作失败');
         } else {
             $this->success('操作成功');
         }
     }
 
     // 评价
     public function rate()
     {
         $busid = $this->request->param('busid', 0, 'trim');
         $leaseid = $this->request->param('leaseid', 0, 'trim');
         $rate = $this->request->param('rate', '', 'trim');
         $comment = $this->request->param('comment', '', 'trim');
 
         $businessinfo = $this->BusinessModel->find($busid);
         if (!$businessinfo) {
             $this->error('用户不存在');
         }
 
         $leaseinfo = $this->LeaseModel->find($leaseid);
 
         if (!$leaseinfo) {
             $this->error('订单不存在');
         }
 
         $data = [
             'id' => $leaseid,
             'comment' => $comment,
             'rate' => $rate,
             'status' => '6',
         ];
 
         $result = $this->LeaseModel->isUpdate()->save($data);
 
         if ($result === false) {
             $this->error('操作失败');
         } else {
             $this->success('操作成功');
         }
     }
}
